<!--
 * @Author: Neil 1294641898@qq.com
 * @Date: 2022-09-04 22:00:30
 * @LastEditors: Neil 1294641898@qq.com
 * @LastEditTime: 2022-09-07 10:46:24
 * @FilePath: \stupid_home\src\components\groups.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="group">
    <van-nav-bar
      title=""
      right-text="退出"
      @click-right="quit"
    />
    <h1 style="margin-top:30px">{{name}}</h1>
    <van-divider>原子云设备分组</van-divider>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text=""
    >
      <div @click="()=>selectGroup(item)" class="listbox" v-for="item in list" :key="item.id">
        <div >{{"分组名称:"+item.name}}</div>
        <div>{{"设备数量:1"}}</div>
      </div>
    </van-list>
  </div>
</template>

<script>


export default {
  props: {},
  data() {
    return {
      //原子云唯一表示token，由官网获得，注册时录入数据库，登陆时后端返回
      token: "",
      // 机构id，机构唯一表示，用于查询设备分组列表
      org_id: "",
      // 机构名称 
      name: "",
      list: [],
      loading: false,
      finished: false,
    };
  },

  methods: {
    async getRouterData() {
      this.token = localStorage.getItem("token")
      console.log("token",this.token);
      await this.getOrgId()
      console.log("org_id", this.org_id);
      await this.getGroupList()
      console.log(this.list);
    },
    //由token拿到org_id,token在main.js里全局配置了
    async getOrgId() {
      await this.$axios.get("api/orgs", {
        headers: {
          "token":this.token
        }
      }).then((res) => {
        //拿到机构id
        if (res.data.code == 200) {
          this.org_id = res.data.data[0].id
          this.name = res.data.data[0].name
        }
        else this.$notify({ type: "danger", message: "获取原子云信息失败" })
      }
      )
    },
    //由token和org_id得到设备分组
    async getGroupList() {
      await this.$axios.get(`api/orgs/${this.org_id}/` + 'grouplist', {
        headers: {
          "token":this.token
        }
      }).then((res) => {
        console.log("check grouplist", res);
        this.list = res.data.data;
        this.finished=true
      })
    },
    selectGroup(item) {
      console.log(item.name + " " + item.id + " " + this.org_id);
      localStorage.setItem("org_id",this.org_id)
      localStorage.setItem("group_id",item.id)
      localStorage.setItem("group_name",item.name)
      this.$router.push("/device")
    },
    quit() {
      this.$destroy()
      this.$router.push('/login')
    }
  },
  mounted() {
    this.getRouterData()
  }
};
</script>
<style lang="less" scoped>
.group{
  width: 100%;
  height: 100%;
  overflow: hidden;
  text-align: center;
  color: #2c3e50;
  
  .listbox{
    width: 100%;
    height: 4rem;
    display: flex;
    justify-content: space-around;
  }
}
</style>